require("babel-core/register");
var express = require('express');
var path = require('path');
var glob  = require('glob');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session')
var http = require('http')
var log4js = require('log4js')
var config = require('./config/config')

var app = express();

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//app.use(multer()); // for parsing multipart/form-data

// 添加过滤函数
require('./filters/')(app);

require('./db/index.js');

process.on('uncaughtException', function(err) {
    console.log('Caught exception: ' + err)
});

app.use(log4js.connectLogger(require('./logConfig'), {
    level: 'info',
    format: ':method :url :status'
}));

app.get('/', (req, res) =>{
  res.end('welcome to admin api.')
})

// 静态资源，页面
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, '../client', 'dist')));

// 自动生成router
const controllers = glob.sync('./controllers/**/*.js');
controllers.forEach((file) => {
  const router = new express.Router();
  try {
    require(file)(router);
    app.use('/' + config.version + file.replace('./controllers', '').slice(0, -3), router);
  } catch (err) {
    console.error(err);
  }
});

var sessionId = Math.random().toString(16).slice(2)
app.use(cookieParser(sessionId));
app.use(session({
    secret: sessionId, //与cookieParser中的一致
    resave: true,
    saveUninitialized: true
}))

app.listen(config.port, function() {
    console.log('project run in ' + config.port + ' port')
})

module.exports = app;
